//
//  BattleView.m
//  Dispatch
//
//  Created by hyeyeon on 14. 1. 14..
//  Copyright (c) 2014년 hyeyeon. All rights reserved.
//

#import "BattleView.h"

@implementation BattleView
@synthesize responseData, battlingArray, itemArray, imageURL, titleMessage, battlingImages;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = ColorFromRGB(0x413c43);
        appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
        self.responseData = [NSMutableData data];
        
        itemArray = [[NSMutableArray alloc] init];
        battlingImages = [[NSMutableDictionary alloc] init];
        dateFormatter = [[NSDateFormatter alloc] init];
        
        [self makeObject:frame];
        
//        [self requestBattlePage:1];
        [self requestBattleDate:@"1"];
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

#pragma mark - 생성
-(void)makeObject:(CGRect)frame{
    mTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    mTableView.dataSource = self;
    mTableView.delegate = self;
    mTableView.backgroundColor = [UIColor clearColor];
    mTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self addSubview:mTableView];
    
    
//    _refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - mTableView.bounds.size.height, mTableView.frame.size.width, mTableView.bounds.size.height)];
//    _refreshHeaderView.delegate = self;
//    [mTableView addSubview:_refreshHeaderView];
//    [_refreshHeaderView refreshLastUpdatedDate];
    
    
    topMoveButton = [[UIButton alloc] initWithFrame:CGRectMake(mySize.width-10-35, frame.size.height-44-10-35, 35, 35)];
    [topMoveButton setImage:[UIImage imageNamed:@"btn_top"] forState:UIControlStateNormal];
    [topMoveButton addTarget:self action:@selector(topMoveButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:topMoveButton];
}


#pragma mark - 위로가기
-(void)topMoveButtonAction:(id)sender{
    [mTableView setContentOffset:CGPointMake(0, 0) animated:YES];
}

#pragma mark - 무한배틀로 가기
-(void)appearBattlingView:(NSNumber*)number{
    
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    [viewController appearBattlingView:number];
}

#pragma mark - 이미지
-(void)loadAndSaveBattlingImages{
    
    for (int i = 0; i<[self.battlingArray count]; i++) {
        NSString *imgStr = [[self.battlingArray objectAtIndex:i] objectForKey:@"thumb_url"];
        
        [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:imgStr imageBlock:^(UIImage *image) {
            [self.battlingImages setValue:image forKey:[NSString stringWithFormat:@"image_%d",i]];
            if (i == [self.battlingArray count]-1) {
                
                [mTableView reloadData];
                NSLog(@"battlingImages : %@",self.battlingImages);
            }
        } errorBlock:^{
            if (i == [self.battlingArray count]-1) {
                
                [mTableView reloadData];
            }
        }];
    }
    
}

#pragma mark - 몇주차인지 알아내기
-(NSDictionary*)dicDate:(NSString*)string{
    
    

    NSArray *array = [string componentsSeparatedByString:@"."];
    NSString *month = [NSString stringWithFormat:@"%d",[[array objectAtIndex:1] intValue]];
    NSString *week = [array objectAtIndex:2];

    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:month,@"week",week,@"month", nil];
    return dic;
}



#pragma mark - 스크롤잡기

- (void)reloadTableViewDataSource{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	_reloading = YES;
	
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:mTableView];
	
}

#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}

#pragma mark - 네트워크
-(void)requestBattlePage:(NSInteger)page{
    
    NSLog(@"_reloading : %@",_reloading?@"yes":@"no");
    NSLog(@"mTableView.contentOffset.y : %f",mTableView.contentOffset.y);
    
    
    if (duringNetwork) {
        NSLog(@"막음");
        return;
    }
    
    
    currentPage = page;
    if (page <= 1) {
        [itemArray removeAllObjects];
    }
    
    NSString *dataStr = [NSString stringWithFormat:@"page=%d&lang=%@&pagesize=100",page,appDelegate.currentLanguage];
    dataStr = [appDelegate encryptDataURLString:dataStr];

//    NSString *url = [NSString stringWithFormat:@"%@?page=%d&lang=%@",URL_BATTLE_MAIN,page,appDelegate.currentLanguage];

    NSString *url = [NSString stringWithFormat:@"%@?p=%@",URL_BATTLE_MAIN,dataStr];
    [self requestURL:url];
}

-(void)requestBattleDate:(NSString*)date{
    if (duringNetwork) {
        return;
    }
    
    if ([date isEqualToString:@"1"]) {
        [itemArray removeAllObjects];
    }
    
    NSString *dataStr = [NSString stringWithFormat:@"date=%@&lang=%@&pagesize=10",date,appDelegate.currentLanguage];
    dataStr = [appDelegate encryptDataURLString:dataStr];
    NSString *url = [NSString stringWithFormat:@"%@?p=%@",URL_BATTLE_MAIN,dataStr];
    [self requestURL:url];
    
}

-(void)requestURL:(NSString*)url{
    
    [self performSelectorOnMainThread:@selector(startRequestWithURL:) withObject:url waitUntilDone:NO];
}

-(void)startRequestWithURL:(NSString*)url{
    @autoreleasepool {
        
        duringNetwork = YES;
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        if (url) {
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
            [request setHTTPMethod:@"POST"];
            
            NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
            
            if(connection){
                NSLog(@"배틀리스트 네트워크 요청 : %@",url);
            }
            
            //api나오면 여기에 작업
            
            
        }
    }
}




#pragma mark delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    [self.responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connectio{
    
    duringNetwork = NO;
    
    
    NSError *myError = nil;
    NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
    
    self.imageURL = ([appDelegate checkObject:[resultDictionary objectForKey:@"imgurl"]]) ? [resultDictionary objectForKey:@"imgurl"] : nil;
    self.titleMessage = ([appDelegate checkObject:[resultDictionary objectForKey:@"title"]]) ? [resultDictionary objectForKey:@"title"] : nil;
    
    NSLog(@"배틀메인 : %@",resultDictionary);
    
    if ([resultDictionary objectForKey:@"return_code"]) {
        if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0) {
            
            resultDictionary = [resultDictionary objectForKey:@"data"];
            
            NSArray *head= ([appDelegate checkObject:[resultDictionary objectForKey:@"items_head"]]) ? [resultDictionary objectForKey:@"items_head"] : nil;

            
            NSArray *items = ([appDelegate checkObject:[resultDictionary objectForKey:@"items"]]) ? [resultDictionary objectForKey:@"items"] : nil;

            
            isEnd = ([appDelegate checkObject:[resultDictionary objectForKey:@"isend"]]) ? [[resultDictionary objectForKey:@"isend"] boolValue] : NO;
            currentPage++;
            
            if (head) {
                self.battlingArray = head;
                [self loadAndSaveBattlingImages];
            }
            if (items) {
                [itemArray addObjectsFromArray:items];
            }
            
            
            [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0.5f];
            
            [mTableView reloadData];
        }
    }
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    duringNetwork = NO;
    NSLog(@"배틀 네트워크 요청 실패 : %@",error);
    
}


#pragma mark - UITableView Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;   //1:진행중인 배틀 2:지난순위
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else{
        return [self.itemArray count];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 161;
    }else{
        return 124;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        //무한배틀하기
        static NSString *CellIdentifier = @"BattlingCell";
        BattlingTableCell *cell = (BattlingTableCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[BattlingTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            cell.delegate = self;
            cell.backgroundColor = [UIColor clearColor];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell settingBattling:self.battlingArray];
        [cell startAnimation];

        return cell;
        
    }else{
        //지난순위
        static NSString *CellIdentifier = @"battleRankingCell";
        BattleRankingTableCell *cell = (BattleRankingTableCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[BattleRankingTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            cell.delegate = self;
            cell.backgroundColor = [UIColor clearColor];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if ([self.itemArray count] > indexPath.row) {

            cell.dateLabel.text = [[self.itemArray objectAtIndex:indexPath.row] objectForKey:@"date_str"];
        }

        
        cell.firstImage.tag = cell.secondImage.tag = cell.thirdImage.tag = indexPath.row;
        
        
        
        NSArray *array = [[self.itemArray objectAtIndex:indexPath.row] objectForKey:@"stars"];
        if ([array count] <= 3) {
            
            NSString *first = [[array objectAtIndex:0] objectForKey:@"thumb_url"];
            NSString *second = [[array objectAtIndex:1] objectForKey:@"thumb_url"];
            NSString *third = [[array objectAtIndex:2] objectForKey:@"thumb_url"];
            
            
            
            [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:first imageBlock:^(UIImage *image) {
                if (cell.firstImage.tag == indexPath.row) {
                    cell.firstImage.image = image;
                    [appDelegate effectFaceoutTargetView:cell.firstImage];
                }
            } errorBlock:^{
                cell.firstImage.image = nil;
            }];
            
            [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:second imageBlock:^(UIImage *image) {
                if (cell.secondImage.tag == indexPath.row) {
                    cell.secondImage.image = image;
                    [appDelegate effectFaceoutTargetView:cell.secondImage];
                }
            } errorBlock:^{
                cell.secondImage.image = nil;
            }];
            
            [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:third imageBlock:^(UIImage *image) {
                if (cell.thirdImage.tag == indexPath.row) {
                    cell.thirdImage.image = image;
                    [appDelegate effectFaceoutTargetView:cell.thirdImage];
                }
            } errorBlock:^{
                cell.thirdImage.image = nil;
            }];
        }
        
        
        
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        //무한배틀
        
    }else{
        //지난순위보기
        
        NSString *dateStr = [[self.itemArray objectAtIndex:indexPath.row] objectForKey:@"date"];
        ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
        [viewController appearBattleRankingViewWithDate:dateStr];

    }
}



#pragma mark - UIScrollView Delegate
//다음페이지 이동
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (!duringNetwork) {
        
        if (([scrollView contentOffset].y+scrollView.frame.size.height) == [scrollView contentSize].height) {
            //다음페이지이동
//            [self requestBattlePage:currentPage];
            NSString *dateStr = [[self.itemArray objectAtIndex:[self.itemArray count]-1] objectForKey:@"date"];
            [self requestBattleDate:dateStr];
        }
    }
    
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    [viewController sdkHidden:NO];
    topMoveButton.hidden = NO;
}

//업데이트
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
//	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
////    if (!duringNetwork) {
////        if (scrollView.contentOffset.y < -50) {
////            //업뎃
////            NSLog(@"requestBattlePage:! red : %d",_reloading?1:0);
//////            [self requestBattlePage:1];
////        }
////    }
    
    if (!decelerate) {
        
        ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
        [viewController sdkHidden:NO];
        topMoveButton.hidden = NO;
    }
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    [viewController sdkHidden:YES];
    topMoveButton.hidden = YES;
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

@end
